const express = require('express');
const app = express();
const mysql = require('mysql');
const simpleGit = require('simple-git');
const fs = require('fs');
const path = require('path');

// 配置MySQL连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'Root123!',
  database: 'get_docs'
});

// 连接MySQL数据库
connection.connect(err => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
  fetchAndCloneRepositories();
});

let domainList = {};
// 从数据库中读取文档库列表并克隆或更新仓库
function fetchAndCloneRepositories() {
  const query = 'SELECT * FROM document_libraries';
  connection.query(query, (err, results) => {
    if (err) throw err;

    results.forEach(library => {
      const repoDir = `${library.dir}`;
      if (!fs.existsSync(repoDir)) {
        // 克隆仓库
        simpleGit().clone(library.git_address, repoDir, (err) => {
          if (err) throw err;
          console.log(`Cloned repository for ${library.dir}`);
        });
      } else {
        // 更新仓库
        simpleGit(repoDir).pull((err, update) => {
          if (err) throw err;
          console.log(`Pulled repository for ${library.dir}:`, update.summary);
        });
      }
      domainList[library.domain] = library.dir;
    });
  });
}

// 设置路由，根据域名响应不同目录的文档内容
app.get('*', (req, res) => {
  const host = req.headers.host; // 获取请求头中的host
  let filePath = req.params[0]; // 获取请求的文件路径
  
  if (filePath === '/')
    filePath = '/index.html';

  const libraryId = domainList[host];
  const repoDir = path.join(__dirname, `${libraryId}`); // 确保路径是基于当前js文件所在目录
  const fullPath = path.join(repoDir, filePath);

  // 检查文件是否存在
  if (fs.existsSync(fullPath)) {
    res.sendFile(fullPath);
  } else {
    res.status(404).send('File not found');
  }
});

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
